package com.example.april.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        boolean matchLogin = new AntPathMatcher().match("/april/login", requestURI);
        boolean matchRoot = new AntPathMatcher().match("/april/", requestURI);
        boolean matchOAuth = new AntPathMatcher().match("/april/OAuth2/**", requestURI);


        if (matchLogin | matchRoot | matchOAuth){
            return true;
        }

        String userId = (String)request.getSession().getAttribute("id");
        if (userId == null || StringUtils.isBlank(userId)){
            response.sendRedirect("http://localhost:8080/april");
            return false;
        }else{
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        /*UserInfoTo userInfoTo = threadLocal.get();
        applicationContext.get
        if (!userInfoTo.getTempUser()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME,userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
*/
    }
}
